﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using HRM.HRMServiceProxy;


namespace HRM
{
    public partial class frmSalaryList : DockContent
    {
        BranchClient wcfBranch;
        DepartmentClient wcfDepartment;
        EmployeeClient wcfEmployee;
        EmployeeInfo _EmployeeInfo;
        SalaryClient wcfSalary;
        SalaryInfo _SalaryInfo;
        PositionDetailClient wcfPD;
        LeaveWorkClient wcfFM;
        LabourContractClient wcfLC;
        ParameterClient wcfParameter;
        MainServiceClient wcfMainService;
        AdvancePaymentClient wcfAdvance;
        AwardClient wcfAward;

        int _month = DateTime.Now.Month;
        int _year = DateTime.Now.Year;
        int _salaryID;
        int _EmployeeID;
        int _DepartmentID;
        int _BranchID, TagID;
        decimal _TotalDate;
        int _countDependent;
        decimal _SocialPercent, _MedicalPercent, _BasicSalary, _FamilySalary, _TotalFamilySalary;
        decimal _SocialInc, _MedicalInc;
        decimal _FactorLeave, _TradeUnion;
        int pageSize = UIParamater.pageSize;
        int currPage = 0;
        int itemCount = 0;
        int totalPage = 0;
        bool _SocialEmployee;
        bool _MedicalEmployee;
        bool _StatusSalary;
        bool _IsInsurance;
        bool _loadedData = false;
        RoleRightInfo listRole;
        int _EmpDate, _JoiningDay, _CloseBookDay;
        MarkWorkClient wcfMarkWork;
        decimal _TotalOverTime;
        int _TotalDateCompany;
        decimal _UnemployedIns;
        decimal _UnemployedInsCompany;
        DateTime _FromDate;
        DateTime _ToDate;

        public frmSalaryList()
        {
            InitializeComponent();
            LoadLanguage();
            wcfBranch = Service.Branch();
            wcfDepartment = Service.Department();
            wcfSalary = Service.Salary();
            wcfMarkWork = Service.MarkWork();
            wcfEmployee = Service.Employee();
            wcfParameter = Service.Parameter();
            wcfPD = Service.PositionDetail();
            wcfLC = Service.LabourContract();
            wcfAdvance = Service.AdvancePayment();
            wcfAward = Service.Award();
            wcfFM = Service.LeaveWork();
            wcfMainService = Service.MainService();
            wcfSalary = Service.Salary();
            wcfEmployee = Service.Employee();

            UISetting.LoadTreeView3(ref tvBranch);
            Addcolumn();

            UISetting.LoadMonths(ref cboMonth);
            cboMonth.ComboBox.SelectedValue = Convert.ToInt32(DateTime.Now.Month);

            UISetting.LoadYears(ref cboYear);
            //cboYear.ComboBox.SelectedValue = Convert.ToUInt32(DateTime.Now.Year);

            listRole = UIParamater.Quyen_BangLuong;
            if (!listRole.Update)
            {
                this.btnEdit.Image = Properties.Resources.app;
                this.btnEdit.Tag = "xem";
            }

            LoadData();
            this.KeyPreview = true;

        }


        private void LoadLanguage()
        {
            this.TabText = this.Text = UpdateUI.GetString(this.Tag.ToString());
            UpdateUI.Load_ToolStrip(ref toolStrip1);
        }

        private void Addcolumn()
        {
            UISetting.AddColumn(ref dgvSalary, "Salary_ID", "Mã chính", "", 1, false, true);
            UISetting.AddColumn(ref dgvSalary, "RowNumber", "", "C", 50, true, true);
            UISetting.AddColumn(ref dgvSalary, "FullName", "", "", 140, true, true);
            UISetting.AddColumn(ref dgvSalary, "Position_Name", "", "", 120, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_Date", "", "C", 60, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_BasicFactor", "", "R", 130, false, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_Basic", "", "R", 130, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_PositionFactor", "", "R", 130, false, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_Position", "", "R", 130, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_OtherResponse", "", "R", 130, false, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_LaterSalary", "", "R", 130, false, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_Award", "", "R", 130, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_TotalDateWork", "", "R", 130, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_TotalDateOutWork", "", "R", 130, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_TotalLeavePaid", "", "R", 130, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_TotalLeaveUnPaid", "", "R", 130, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_OverTime", "", "R", 130, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_ProbationFactor", "", "R", 130, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_TradeUnion", "", "R", 130, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_IncomeTax", "", "R", 130, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_Advance", "", "R", 130, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_OtherDeduction", "", "R", 130, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_EmployeeSocialIns", "", "R", 130, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_EmployeeMedicalIns", "", "R", 130, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_SocialIns", "", "R", 130, true, true);
            UISetting.AddColumn(ref dgvSalary, "Salary_MedicalIns", "", "R", 130, true, true);
            UISetting.AddColumn(ref dgvSalary, "TotalSalaryEarn", "", "R", 130, true, true);
        }

        private void PageIndex()
        {
            totalPage = itemCount % pageSize > 0 ? (itemCount / pageSize) + 1 : (itemCount / pageSize);
            if (totalPage == 0)
                lblPageIndex.Text = "0" + "/" + totalPage.ToString();
            else
                lblPageIndex.Text = (currPage + 1).ToString() + "/" + totalPage.ToString();
        }

        private void LoadData()
        {
            _month = Convert.ToInt32(cboMonth.Text);
            int temptYear;
            if (Int32.TryParse(cboYear.Text, out temptYear))
                _year = temptYear;
            DataSet ds = wcfSalary.Salary_GetList(out itemCount, currPage, pageSize, _BranchID, _DepartmentID, _month, _year);
            PageIndex();
            dgvSalary.Rows.Clear();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                dgvSalary.Rows.Insert(i, 1);
                dgvSalary.Columns["Position_Name"].Frozen = true;
                dgvSalary.Rows[i].Cells["Salary_ID"].Value = ds.Tables[0].Rows[i]["Salary_ID"].ToString();
                dgvSalary.Rows[i].Cells["RowNumber"].Value = ds.Tables[0].Rows[i]["RowNumber"].ToString();
                dgvSalary.Rows[i].Cells["FullName"].Value = ds.Tables[0].Rows[i]["FullName"].ToString();
                dgvSalary.Rows[i].Cells["Position_Name"].Value = ds.Tables[0].Rows[i]["Position_Name"].ToString();
                dgvSalary.Rows[i].Cells["Salary_Date"].Value = Convert.ToDateTime(ds.Tables[0].Rows[i]["Salary_Date"]).ToString("MM/yyyy");
                dgvSalary.Rows[i].Cells["Salary_BasicFactor"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_BasicFactor"]).ToString(UIParamater.Cham2So);
                dgvSalary.Rows[i].Cells["Salary_Basic"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_Basic"]).ToString(UIParamater.Phay2So);
                dgvSalary.Rows[i].Cells["Salary_PositionFactor"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_PositionFactor"]).ToString(UIParamater.Cham2So);
                dgvSalary.Rows[i].Cells["Salary_Position"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_Position"]).ToString(UIParamater.Phay2So);
                dgvSalary.Rows[i].Cells["Salary_OtherResponse"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_OtherResponse"]).ToString(UIParamater.Phay2So);
                dgvSalary.Rows[i].Cells["Salary_LaterSalary"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_LaterSalary"]).ToString(UIParamater.Phay2So);
                dgvSalary.Rows[i].Cells["Salary_Award"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_Award"]).ToString(UIParamater.Phay2So);
                dgvSalary.Rows[i].Cells["Salary_TotalDateWork"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_TotalDateWork"]).ToString(UIParamater.Cham2So);
                dgvSalary.Rows[i].Cells["Salary_TotalDateOutWork"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_TotalDateOutWork"]).ToString(UIParamater.Cham2So);
                dgvSalary.Rows[i].Cells["Salary_TotalLeavePaid"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_TotalLeavePaid"]).ToString(UIParamater.Cham2So);
                dgvSalary.Rows[i].Cells["Salary_TotalLeaveUnPaid"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_TotalLeaveUnPaid"]).ToString(UIParamater.Cham2So);
                dgvSalary.Rows[i].Cells["Salary_OverTime"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_OverTime"]).ToString(UIParamater.Cham2So);
                dgvSalary.Rows[i].Cells["Salary_ProbationFactor"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_ProbationFactor"]).ToString(UIParamater.Cham2So);
                dgvSalary.Rows[i].Cells["Salary_TradeUnion"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_TradeUnion"]).ToString(UIParamater.Phay2So);
                dgvSalary.Rows[i].Cells["Salary_IncomeTax"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_IncomeTax"]).ToString(UIParamater.Phay2So);
                dgvSalary.Rows[i].Cells["Salary_Advance"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_Advance"]).ToString(UIParamater.Phay2So);
                dgvSalary.Rows[i].Cells["Salary_OtherDeduction"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_OtherDeduction"]).ToString(UIParamater.Phay2So);
                dgvSalary.Rows[i].Cells["Salary_EmployeeSocialIns"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_EmployeeSocialIns"]).ToString(UIParamater.Phay2So);
                dgvSalary.Rows[i].Cells["Salary_EmployeeMedicalIns"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_EmployeeMedicalIns"]).ToString(UIParamater.Phay2So);
                dgvSalary.Rows[i].Cells["Salary_SocialIns"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_SocialIns"]).ToString(UIParamater.Phay2So);
                dgvSalary.Rows[i].Cells["Salary_MedicalIns"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["Salary_MedicalIns"]).ToString(UIParamater.Phay2So);
                dgvSalary.Rows[i].Cells["TotalSalaryEarn"].Value = Convert.ToDecimal(ds.Tables[0].Rows[i]["TotalSalaryEarn"]).ToString(UIParamater.Phay2So);
            }
            _loadedData = true;
            //dgvSalary.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
        }

        private void btnSalary_Click(object sender, EventArgs e)
        {
            if (!listRole.Update)
            {
                MessageBox.Show(UpdateUI.GetString("khongcoquyencapnhat"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (TagID == 0)
            {
                MessageBox.Show(UpdateUI.GetString("chuachonchinhanh"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            frmProgressbar f = new frmProgressbar();
            f.Show(this);
            f.Refresh();
            Application.DoEvents();

            _month = Convert.ToInt32(cboMonth.Text);
            int temptYear;
            if (Int32.TryParse(cboYear.Text, out temptYear))
                _year = temptYear;
            try
            {

                //Lấy dữ liệu từ bảng Parameter:
                _TotalDateCompany = Convert.ToInt32(wcfParameter.Parameter_GetByName("TotalDateWork").Value);
                _BasicSalary = Convert.ToDecimal(wcfParameter.Parameter_GetByName("MinBasicSalary").Value);
                _FamilySalary = Convert.ToDecimal(wcfParameter.Parameter_GetByName("FamilySalary").Value);
                _CloseBookDay = Convert.ToInt32(wcfParameter.Parameter_GetByName("CloseBook").Value);
                _JoiningDay = Convert.ToInt32(wcfParameter.Parameter_GetByName("Joining").Value);
                _MedicalPercent = Convert.ToDecimal(wcfParameter.Parameter_GetByName("MedicalInsurancePercentLabour").Value) / 100;
                _SocialPercent = Convert.ToDecimal(wcfParameter.Parameter_GetByName("SocialInsurancePercentLabour").Value) / 100;
                _SocialInc = Convert.ToDecimal(wcfParameter.Parameter_GetByName("SocialInsurancePercent").Value) / 100;
                _MedicalInc = Convert.ToDecimal(wcfParameter.Parameter_GetByName("MedicalInsurancePercent").Value) / 100;
                _UnemployedIns = Convert.ToDecimal(wcfParameter.Parameter_GetByName("UnemployedIns").Value) / 100;
                _UnemployedInsCompany = Convert.ToDecimal(wcfParameter.Parameter_GetByName("UnemployedInsCompany").Value) / 100;
                _TradeUnion = Convert.ToDecimal(wcfParameter.Parameter_GetByName("TradeUnion").Value) / 100;
                _ToDate = UISetting.GetDate(_CloseBookDay + "/" + cboMonth.Text + "/" + _year);
                _FromDate = _ToDate.AddMonths(-1);
                _TotalDate = wcfEmployee.Employee_CountTotalDateWork(_FromDate, _ToDate);

                //Lấy dữ liệu Department theo Branch:
                DataTable dtDepart = wcfDepartment.Department_GetAllWithBranch(_BranchID).Tables[0];
                foreach (DataRow drDepart in dtDepart.Rows)
                {
                    _DepartmentID = Convert.ToInt32(drDepart["Department_ID"]);

                    //Lấy dữ liệu từ bảng PositionDetail theo Department:
                    DataTable dtPD = wcfPD.PositionDetail_GetWithDepartment(_DepartmentID).Tables[0];
                    foreach (DataRow drPD in dtPD.Rows)
                    {
                        _EmployeeID = Convert.ToInt32(drPD["PD_EmployeeID"].ToString());

                        //Gán giá trị vào bảng lương
                        _SalaryInfo = new SalaryInfo();
                        _SalaryInfo.ID = _salaryID;
                        _SalaryInfo.EmployeeID = _EmployeeID;
                        _SalaryInfo.BasicFactor = Convert.ToDecimal(drPD["PD_BasicSalary"]);
                        _BasicSalary = Convert.ToDecimal(drPD["PD_BasicSalary"]);
                        _SalaryInfo.PositionFactor = drPD["PD_PositionAllowance"] == DBNull.Value ? 0 : Convert.ToDecimal(drPD["PD_PositionAllowance"]);
                        _SalaryInfo.Date = DateTime.ParseExact(cboMonth.Text + "/" + cboYear.Text, "MM/yyyy", null);

                        //Lấy dữ liệu từ bảng MarkWork: Đối chiếu ngày công
                        DataTable dtMW = wcfMarkWork.MarkWork_GetWithEmployee(_EmployeeID, _ToDate).Tables[0];
                        _TotalDate = dtMW.Rows[0]["TotalDateWork"] == DBNull.Value ? 0 : Convert.ToDecimal(dtMW.Rows[0]["TotalDateWork"].ToString());
                        _TotalOverTime = dtMW.Rows[0]["TotalOverTime"] == DBNull.Value ? 0 : Convert.ToDecimal(dtMW.Rows[0]["TotalOverTime"].ToString());

                        //Lấy dữ liệu từ bảng LabourContract:
                        DataTable dtLC = wcfLC.LabourContract_GetWithEmployee(_EmployeeID).Tables[0];
                        DateTime _LC_FromDate = DateTime.MinValue;
                        DateTime _LC_ToDate = DateTime.MinValue;
                        if (dtLC.Rows.Count > 0)
                        {
                            _SalaryInfo.ProbationFactor = dtLC.Rows[0]["ContractType_Probation"] == DBNull.Value ? 0 : Convert.ToDecimal(dtLC.Rows[0]["ContractType_Probation"]);
                            
                            _IsInsurance = dtLC.Rows[0]["ContractType_Insurance"] == DBNull.Value ? false : Convert.ToBoolean(dtLC.Rows[0]["ContractType_Insurance"]);
                            _LC_FromDate = dtLC.Rows[0]["LC_BeginDate"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(dtLC.Rows[0]["LC_BeginDate"]);
                            _LC_ToDate = dtLC.Rows[0]["LC_FinishDate"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(dtLC.Rows[0]["LC_FinishDate"]);

                            //Nếu trong tháng có nhân viên hết hạn hợp đồng thì thông báo gia hạn hợp đồng
                            //số ngày làm = ngày hết hạn trừ đi ngày chốt sổ tháng trước:
                            /*
                            _EmployeeInfo = wcfEmployee.Employee_GetInfo(_EmployeeID);

                            if (_LC_ToDate.Month == _ToDate.Month && _LC_ToDate.Year == _ToDate.Year)
                            {
                                MessageBox.Show("Nhân viên: " + _EmployeeInfo.LastName + " " + _EmployeeInfo.FirstName + " cần gia hạn hợp đồng", "Thông báo", MessageBoxButtons.OK);
                            }
                             */
                        }

                        //Lấy dữ liệu từ bảng AdvancePayment:
                        DataTable dtAdvance = wcfAdvance.AdvancePayment_GetWithEmployee(_EmployeeID, _month, _year).Tables[0];
                        if (dtAdvance.Rows.Count > 0)
                            _SalaryInfo.Advance =dtAdvance.Rows[0]["AdvancePayment_AmountPayment"]==DBNull.Value?0: Convert.ToDecimal(dtAdvance.Rows[0]["AdvancePayment_AmountPayment"]);
                        else
                            _SalaryInfo.Advance = 0;

                        //Lấy dữ liệu từ bảng Award:
                        if (wcfAward.Award_CheckExistEmployee(_EmployeeID, _month, _year))
                            _SalaryInfo.Award = wcfAward.Award_GetInfoEmployee(_EmployeeID).Amount;


                        //Lấy dữ liệu từ bảng LeaveWork:
                        if (wcfFM.LeaveWork_CheckExistEmployee(_EmployeeID, _month, _year))
                        {
                            DataTable dtFM = wcfFM.LeaveWork_GetWithEmployee(_EmployeeID, _ToDate).Tables[0];
                            if (dtFM.Rows[0]["TotalDateOutWork"] == DBNull.Value)
                                _SalaryInfo.TotalDateOutWork = 0;
                            else if (Convert.ToDecimal(dtFM.Rows[0]["TotalDateOutWork"]) > 26)
                                _SalaryInfo.TotalDateOutWork = 26;
                            else
                                _SalaryInfo.TotalDateOutWork = Convert.ToDecimal(dtFM.Rows[0]["TotalDateOutWork"]);

                            if (dtFM.Rows[0]["TotalDateWorkPaid"] == DBNull.Value)
                                _SalaryInfo.TotalLeavePaid = 0;
                            //else if (Convert.ToInt32(dtFM.Rows[0]["TotalDateWorkPaid"]) > 26)
                            //    _SalaryInfo.TotalLeavePaid = 26;
                            else
                                _SalaryInfo.TotalLeavePaid = Convert.ToDecimal(dtFM.Rows[0]["TotalDateWorkPaid"]);

                            if (dtFM.Rows[0]["TotalDateWorkUnPaid"] == DBNull.Value)
                                _SalaryInfo.TotalLeaveUnPaid = 0;
                            else if (Convert.ToDecimal(dtFM.Rows[0]["TotalDateWorkUnPaid"]) > 26)
                                _SalaryInfo.TotalLeaveUnPaid = 26;
                            else
                                _SalaryInfo.TotalLeaveUnPaid = Convert.ToDecimal(dtFM.Rows[0]["TotalDateWorkUnPaid"]);

                            _FactorLeave = Convert.ToDecimal(dtFM.Rows[0]["FactorSalary"]);
                            _SocialEmployee = Convert.ToBoolean(dtFM.Rows[0]["SocialInsurance"]);
                            _MedicalEmployee = Convert.ToBoolean(dtFM.Rows[0]["MedicalInsurance"]);
                            _StatusSalary = Convert.ToBoolean(dtFM.Rows[0]["StatusSalary"]);
                        }
                        else
                        {
                            _SalaryInfo.TotalDateOutWork = 0;
                            _SalaryInfo.TotalLeavePaid = 0;
                            _SalaryInfo.TotalLeaveUnPaid = 0;
                        }

                        //Lấy dữ liệu từ bảng Family để tính số người phụ thuộc:
                        
                        string _sql = "SELECT COUNT(Family_ID) AS Number FROM HRM_Family WHERE Family_EmployeeID = " + _EmployeeID + " AND Family_IsDependent = 'true'";
                        DataTable dt = wcfMainService.Query(_sql).Tables[0];
                        _countDependent = Convert.ToInt32(dt.Rows[0]["Number"]);
                        _TotalFamilySalary = _countDependent * _FamilySalary;

                        //Lấy dữ liệu từ bảng Employee: 
                        //kiểm tra tháng trước nhân viên xem có phải là nhân viên mới không?
                        decimal _day = 0;
                        decimal _NewOverTime = 0;
                        //DataTable dtNewMember;
                        DateTime _CheckDate = DateTime.MinValue;
                        _CheckDate = UISetting.GetDate("01/" + cboMonth.Text + "/" + _year);

                        //if (wcfEmployee.Employee_ChechNewMember(_EmployeeID, _CheckDate.AddMonths(-1)))
                        //{
                        //    _EmpDate = wcfEmployee.Employee_GetInfo(_EmployeeID).StartDate.Day;

                        //    //Nếu ngày vào lớn hơn ngày Joining của tham số hệ thống:
                        //    if (_EmpDate > _JoiningDay)
                        //    {
                        //        //_day = wcfEmployee.Employee_CountDateWorkNewMember(_EmployeeID, _ToDate.AddMonths(-1));
                        //        dtNewMember = wcfMarkWork.MarkWork_CountDateWorkNewMember(_EmployeeID, _ToDate.AddMonths(-1)).Tables[0];
                        //        _day = Convert.ToDecimal(dtNewMember.Rows[0]["TotalDateWork"]);
                        //        if (dtNewMember.Rows[0]["TotalOverTime"] != DBNull.Value)
                        //            _NewOverTime = Convert.ToDecimal(dtNewMember.Rows[0]["TotalOverTime"]);
                        //    }
                        //}

                        // Nếu trong tháng là nhân viên mới thì 
                        // tổng ngày làm là từ ngày vào công ty cho đến ngày đóng sổ lương
                        //if (wcfEmployee.Employee_ChechNewMember(_EmployeeID, _CheckDate))
                        //{
                        //    dtNewMember = wcfMarkWork.MarkWork_CountDateWorkNewMember(_EmployeeID, _ToDate).Tables[0];
                        //    _TotalDate = Convert.ToDecimal(dtNewMember.Rows[0]["TotalDateWork"]);
                        //    if (dtNewMember.Rows[0]["TotalOverTime"] != DBNull.Value)
                        //        _TotalOverTime = Convert.ToDecimal(dtNewMember.Rows[0]["TotalOverTime"]);
                        //}


                        //Tính lương:
                        _SalaryInfo = BasicSalary.TinhLuongMayChamCong(_SalaryInfo, _TotalDateCompany,
                            _TotalDate, _TotalOverTime, _day, _NewOverTime, _BasicSalary,
                            _TotalFamilySalary, _SocialPercent, _MedicalPercent,
                            _SocialInc, _MedicalInc, _SocialEmployee, _MedicalEmployee, _TradeUnion,
                            _UnemployedIns, _UnemployedInsCompany, _FactorLeave, _IsInsurance);



                        if (wcfSalary.Salary_CheckExistEmployee(_EmployeeID, _month, _year))
                        {//update

                            if (wcfSalary.Salary_Update(_SalaryInfo))
                            {
                                Program.taskbarNotifier.Show(UpdateUI.GetString("thongbao"), UpdateUI.GetString("capnhatthanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                            }
                            else
                                MessageBox.Show(UpdateUI.GetString("capnhatkhongthanhcong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else//insert
                        {
                            if (_SalaryInfo.ProbationFactor != 0)
                            {
                                //if (_SalaryInfo.TotalDateWork > 0)
                                //{
                                //Lấy dữ liệu từ bảng Employee: kiểm tra nhân viên xem có phải là nhân viên mới không?
                                if (wcfEmployee.Employee_CheckNewMember(_EmployeeID, _CheckDate))
                                {
                                    _EmpDate = wcfEmployee.Employee_GetInfo(_EmployeeID).StartDate.Day;

                                    //Nếu ngày vào nhỏ hơn ngày Joining của tham số hệ thống:
                                    if (_EmpDate < _JoiningDay)
                                    {
                                        //Kiểm tra ngày kết thúc hợp đồng:
                                        _SalaryInfo.ID = wcfSalary.Salary_Insert(_SalaryInfo);
                                        if (_SalaryInfo.ID > 0)
                                        {
                                            Program.taskbarNotifier.Show(UpdateUI.GetString("thongbao"), UpdateUI.GetString("capnhatthanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                                        }
                                        else
                                            MessageBox.Show(UpdateUI.GetString("capnhatkhongthanhcong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    }
                                }
                                else
                                {
                                    _SalaryInfo.ID = wcfSalary.Salary_Insert(_SalaryInfo);
                                    if (_SalaryInfo.ID > 0)
                                    {
                                        Program.taskbarNotifier.Show(UpdateUI.GetString("thongbao"), UpdateUI.GetString("capnhatthanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                                    }
                                    else
                                        MessageBox.Show(UpdateUI.GetString("capnhatkhongthanhcong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                }

                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                f.Close();
            }

        }

        private void btnFisrt_Click(object sender, EventArgs e)
        {
            currPage = 0;
            if (TagID == 0)
                LoadData();
            else if (TagID == 1)
                LoadData();
            else if (TagID == 2)
                LoadData();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (totalPage > 0 && currPage < totalPage - 1)
                currPage++;
            if (TagID == 0)
                LoadData();
            else if (TagID == 1)
                LoadData();
            else if (TagID == 2)
                LoadData();
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if (currPage > 0)
                currPage--;
            if (TagID == 0)
                LoadData();
            else if (TagID == 1)
                LoadData();
            else if (TagID == 2)
                LoadData();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            if (totalPage > 0)
                currPage = totalPage - 1;
            if (TagID == 0)
                LoadData();
            else if (TagID == 1)
                LoadData();
            else if (TagID == 2)
                LoadData();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dgvSalary.SelectedRows.Count > 0)
            {
                if (listRole.Update || listRole.View)
                {
                    _salaryID = Convert.ToInt32(dgvSalary.SelectedRows[0].Cells["Salary_ID"].Value);
                    Form f = new frmSalaryInfo(_salaryID, listRole);
                    if (f.ShowDialog(this) == DialogResult.OK)
                    {
                        LoadData();
                    }
                }
                else
                    MessageBox.Show(UpdateUI.GetString("khongcoquyenxem"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void dgvSalary_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
                btnEdit_Click(null, null);
        }

        private void frmSalaryList_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    if (!e.Alt && !e.Control)
                    {
                        this.ProcessTabKey(!e.Shift);
                        e.Handled = true;
                    }
                    break;
                case Keys.Escape:
                    this.Dispose();
                    this.Close();
                    break;
                case Keys.F2:
                    btnSalary_Click(null, null);
                    break;
                case Keys.F3:
                    btnEdit_Click(null, null);
                    break;
            }
        }

        private void tvBranch_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Level == 0)
            {
                _BranchID = 0;
                _DepartmentID = 0;
                LoadData();
                TagID = 0;
            }
            else if (e.Node.Level == 1)
            {
                _BranchID = Convert.ToInt32(e.Node.Tag);
                _DepartmentID = 0;
                currPage = 0;
                LoadData();
                TagID = 1;
            }
            else if (e.Node.Level >= 2)
            {
                _BranchID = Convert.ToInt32(GetBranchNode(e.Node).Tag);
                _DepartmentID = Convert.ToInt32(e.Node.Tag);
                currPage = 0;
                LoadData();
                TagID = 2;
            }
        }
        TreeNode GetBranchNode(TreeNode node)
        {
            TreeNode retVal = node;
            if (node.Level >= 2)
                retVal = node.Parent;
            return retVal;
        }
        private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_loadedData)
            {
                currPage = 0;
                if (TagID == 0)
                    LoadData();
                else if (TagID == 1)
                    LoadData();
                else if (TagID == 2)
                    LoadData();
            }
        }

        private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (_loadedData)
            {
                currPage = 0;
                if (TagID == 0)
                    LoadData();
                else if (TagID == 1)
                    LoadData();
                else if (TagID == 2)
                    LoadData();
            }
        }

        private void frmSalaryList_Activated(object sender, EventArgs e)
        {
            LoadLanguage();
            if (dgvSalary.Columns.Count > 0)
            {
                dgvSalary.Columns["RowNumber"].HeaderText = UpdateUI.GetString("stt");
                dgvSalary.Columns["FullName"].HeaderText = UpdateUI.GetString("hovaten");
                dgvSalary.Columns["Position_Name"].HeaderText = UpdateUI.GetString("chucvu");
                dgvSalary.Columns["Salary_Date"].HeaderText = UpdateUI.GetString("thang");
                dgvSalary.Columns["Salary_BasicFactor"].HeaderText = UpdateUI.GetString("hesoluongcoban");
                dgvSalary.Columns["Salary_PositionFactor"].HeaderText = UpdateUI.GetString("hesophucapchucvu");
                dgvSalary.Columns["Salary_Basic"].HeaderText = UpdateUI.GetString("tienluongcoban");
                dgvSalary.Columns["Salary_Position"].HeaderText = UpdateUI.GetString("phucapchucvu");
                dgvSalary.Columns["Salary_OtherResponse"].HeaderText = UpdateUI.GetString("phucapkhac");
                dgvSalary.Columns["Salary_LaterSalary"].HeaderText = UpdateUI.GetString("tientruylinh");
                dgvSalary.Columns["Salary_Award"].HeaderText = UpdateUI.GetString("khenthuong");
                dgvSalary.Columns["Salary_TotalDateWork"].HeaderText = UpdateUI.GetString("songaydilam");
                dgvSalary.Columns["Salary_TotalDateOutWork"].HeaderText = UpdateUI.GetString("songaynghiviec");
                dgvSalary.Columns["Salary_TotalLeavePaid"].HeaderText = UpdateUI.GetString("nghicoluong");
                dgvSalary.Columns["Salary_TotalLeaveUnPaid"].HeaderText = UpdateUI.GetString("nghikhongluong");
                dgvSalary.Columns["Salary_OverTime"].HeaderText = UpdateUI.GetString("sogiolamthem");
                dgvSalary.Columns["Salary_ProbationFactor"].HeaderText = UpdateUI.GetString("tyleluong");
                dgvSalary.Columns["Salary_TradeUnion"].HeaderText = UpdateUI.GetString("phicongdoan");
                dgvSalary.Columns["Salary_IncomeTax"].HeaderText = UpdateUI.GetString("thuethunhap");
                dgvSalary.Columns["Salary_Advance"].HeaderText = UpdateUI.GetString("tamung");
                dgvSalary.Columns["Salary_OtherDeduction"].HeaderText = UpdateUI.GetString("giamkhac");
                dgvSalary.Columns["Salary_EmployeeSocialIns"].HeaderText = UpdateUI.GetString("baohiemxahoinhanvien");
                dgvSalary.Columns["Salary_EmployeeMedicalIns"].HeaderText = UpdateUI.GetString("baohiemytenhanvien");
                dgvSalary.Columns["Salary_SocialIns"].HeaderText = UpdateUI.GetString("baohiemxahoicongty");
                dgvSalary.Columns["Salary_MedicalIns"].HeaderText = UpdateUI.GetString("baohiemytecongty");
                dgvSalary.Columns["TotalSalaryEarn"].HeaderText = UpdateUI.GetString("tongtiennhanvienduoclinh");

            }
        }
    }
}
